// PSPSortByStandard.cpp: implementation of the PSPSortByStandard class.
//
//////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include "PSPSortByStandard.h"
#include "Standard.h"
#include "ProductCatalog.h"
#include "ProductCatalogManager.h"
#include "PersistentFacade.h"
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

PSPSortByStandard::PSPSortByStandard()
{

}

PSPSortByStandard::~PSPSortByStandard()
{

}

BOOL PSPSortByStandard::SetStandard(const CString& strStandard)
{
	ASSERT(!strStandard.IsEmpty());
	if(m_Set.GetDataStandard() == strStandard)
		return TRUE;

	m_Set.SetDataStandard(strStandard);
	Standard* pStandard = NULL;
	ProductCatalog* pCatalog = ProductCatalogManager::Instance()->GetProductCatalog(m_Set.GetDataStandard());
	ASSERT(pCatalog);

	pStandard = GetPersistentFacade().GetStandardGenerator()->Generate(pCatalog);
	ASSERT(pStandard);

	CString strSql;
	strSql.Format(_T("Select * from %s "), pStandard->GetIDDataTable());

	BOOL bResult = FALSE;
	_RecordsetPtr rs;
	try
	{
		const _ConnectionPtr* pCon = pCatalog->DataSourceConnection();
		ASSERT(pCon);

		rs = (*pCon)->Execute(_bstr_t(strSql), NULL, adCmdText);

		ASSERT(rs != NULL);
		
		bResult = ReadProperty(rs);
		rs->Close();
	}
	CATCH_COM_ERROR(rs, FALSE)
	
	return bResult;	

}

BOOL PSPSortByStandard::ReadProperty(const _RecordsetPtr& rs)
{
	if(rs->adoEOF && rs->BOF)
		return TRUE;

	PartSortProperty* pProperty = NULL;
	try
	{
		rs->MoveFirst();
		while(!rs->adoEOF && !rs->BOF)
		{
			pProperty = new PartSortProperty;
			ASSERT(pProperty);
			
			ASSERT(!GetStandard().IsEmpty());
			pProperty->Standard(this->GetStandard());
			pProperty->CustomID(vtos(rs->GetCollect(_T("CustomID"))));
			pProperty->ID(vtos(rs->GetCollect(_T("ID"))));
			pProperty->Index(vtoi(rs->GetCollect(_T("Index"))));
			pProperty->ClassID(vtoi(rs->GetCollect(_T("ClassID"))));
			pProperty->SpecFormat(vtos(rs->GetCollect(_T("BHFormat"))));
			pProperty->BmpName(vtos(rs->GetCollect(_T("Bmpname"))));
			pProperty->Description(vtos(rs->GetCollect(_T("Description"))));
			pProperty->Parent(vtos(rs->GetCollect(_T("Parent"))));
			
			this->Add(pProperty->CustomID(), pProperty);
			rs->MoveNext();
		}
	}
	catch(_com_error e)
	{
		ASSERT(FALSE);
		delete pProperty;
		ErrorAlert(e);
		return FALSE;
	}

	return TRUE;	
}